package servlet.util;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadRequestParser {
	private List<FileItem> items =null;
	public FileUploadRequestParser(HttpServletRequest req) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			items = upload.parseRequest(req);
		} catch (FileUploadException e) {
			throw new RuntimeException("文件上传失败",e);
		}
	}

	public String getFormFileIdValue(String name){
		for (FileItem i : items) {
			if(i.isFormField() && name.equals(i.getFieldName())){
				try {
					return i.getString("UTF-8");
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("文件上传失败",e);
				}
			}
		}
		return null;
	}
	
	public FileItem getFileFieId(String name){
		for (FileItem i : items) {
			if(!i.isFormField() && name.equals(i.getFieldName())){
				return i;
			}
		}
		return null;
	}
}

